package java_thinking.unit_21.Exercise.thread;

import java.util.concurrent.*;

/**
 * @Desc:   future.get 超时则执行cancel去中断线程任务
 * @author: cww
 * @DateTime: 2019-08-04 21:27
 */

public class FutureGetTimeOutTest {
    public static void main(String[] args) {
        int timeOut = 3;
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Boolean result = true;
        Future<Boolean> future = executor.submit(new TaskThread());
        try {
            result = future.get(timeOut, TimeUnit.SECONDS);
            System.out.println("task back result : " + result);
        } catch (InterruptedException e) {
            System.out.println("Thread InterruptedException");
            future.cancel(true);
        } catch (ExecutionException e) {
            System.out.println("Thread ExecutionException");
            future.cancel(true);
        } catch (TimeoutException e) {
            System.out.println("Thread TimeoutException");
            future.cancel(true);
        } finally {
            System.out.println("shutdown ThreadPool");
//            executor.shutdown();
        }
    }

}

class TaskCallable implements Callable<Boolean> {
    private String t;

    public TaskCallable(String threadName) {
        this.t = threadName;
    }

    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i < 999999999; i++) {
            //如果不打印，999999999很快就跑完了还没等到超时，
            System.out.println(i);
            if (i == 999999998) {
                System.out.println(t + " succeeded");
            }
//            Thread.sleep(10000);
            //响应线程中断-很重要
            if (Thread.interrupted()) {
                System.out.println("Thread.interrupted");
                return false;
            }
        }
        System.out.println("continue....");
        return true;
    }
}



class TaskThread implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        Boolean result = false;
        try {
            System.out.println("任务开始....");
            //修改sleep 的值测试超时
            Thread.sleep(50000);
            result = true;
            System.out.println("任务结束....");
        } catch (Exception e) {
            System.out.println("Task is interrupted!");
            throw new InterruptedException("dwdwdw");
        }
        return result;
    }
}